<?php

namespace app\api\controller;

use app\model\Order;
use support\Log;
use support\Request;
use EasyWeChat\Factory;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;


/**
 *  支付
 */
class PaymentController
{
    /**
     * @param $title订单标题
     * @param $trade_no订单编号
     * @param $trade_type微信支付渠道类型
     * @param $amount订单金额
     * @param $openid用户openid
     * @param $notify_url回调地址
     */
    public static function wechatPay($title ,$trade_no, $notify_url, $trade_type = 'APP', $amount = 0, $openid = '')
    {
        $config  = config('payment.wx_pay');

        $amount = '0.01';
        $result  = Factory::payment($config)->order->unify([
            'body' => $title,
            'out_trade_no' => $trade_no,
            'total_fee'    => $amount*100,
            'trade_type'   => $trade_type,
            'openid'       => $openid,
            'notify_url'   => $notify_url
        ]);

        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS')
        {
            switch ($trade_type)
            {
                case 'JSAPI':
                    $pay_info =  Factory::payment($config)->jssdk->bridgeConfig($result['prepay_id'], false);
                    return $pay_info;

                    break;
                case 'NATIVE':

                    break;
                case 'APP':
                    $pay_info = Factory::payment($config)->jssdk->appConfig($result['prepay_id']);
                    return $pay_info;

                    break;
                case 'MWEB':

                    break;
                default:
                    return [];
            }
        }else{
            return [];
        }
    }

    /**
     * 微信支付退款
     * @return
     */
    public static function wechatRefund($order_no , $refund_no, $amount)
    {
        try {
            $app = Factory::payment(config('payment.wx_pay'));

            // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
            $result = $app->refund->byOutTradeNumber($order_no, $refund_no, $amount*100, $amount*100);
            if($result['return_code'] == 'SUCCESS')
            {
                return true;
            }else{
                return $result['err_code_des'];
            }
        }catch (\Exception $e)
        {
            return '微信支付：微信退款申请处理失败';
        }
    }

    /**
     * 查询微信退款结果
     * @param $order_no订单单号
     * @param $refund_no申请退款单号
     * @return
     */
    public static function refundResult($order_no = null, $refund_no = null)
    {
        $app = Factory::payment(config('payment.wx_pay'));

        try {
            if($order_no)
            {
                $result = $app->refund->queryByOutTradeNumber($order_no);  //根据订单号查询退款
            }

            if($refund_no)
            {
                $result = $app->refund->queryByOutRefundNumber($refund_no); //根据退款单号查询退款
            }

            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS')
            {
                return true;
            }else{
                return $result['err_code_des'];
            }
        }catch (\Exception $e)
        {
            return $e;
        }
    }

    /**
     * 申请提现
     * @param $trade_no提现申请单号
     * @param $amount提现金额
     * @return
     */
    public static function withdraw($trade_no, $amount, $openid)
    {
        $app = Factory::payment(config('payment.wx_pay'));
        $res = $app->transfer->toBalance([
            'partner_trade_no' => $trade_no, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $amount*100, // 企业付款金额，单位为分
            'desc' => '提现申请', // 企业付款操作说明信息。必填
        ]);

        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS')
        {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 微信支付订单通知回调
     * @params string
     * @return
     */
    public function wx_order_notify(Request $request)
    {
        $app = Factory::payment(config('payment.wx_pay'));
        $symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
        $symfony_request->headers = new HeaderBag($request->header());
        $app->rebind('request', $symfony_request);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::info('wx_pay_order'.$message['out_trade_no'], $message);

            $order_info = Order::payStatus($message['out_trade_no']);
            if(empty($order_info) || $order_info['is_pay'] == 1)
            {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {

                if($message['result_code'] == 'SUCCESS' && $message['total_fee']/100 == $order_info['order_amount'])
                {
                    //设置订单为已支付
                    Order::setOrderPaySuccess($message['out_trade_no'], $message['total_fee']/100);
                    return true;

                }elseif ($message['result_code'] === 'FAIL') {
                    //支付失败

                    return $fail('notify_result_code_fail');
                }
            }else{
                //回调失败记录
                Log::info('wx_pay_fail_order'.$message['out_trade_no'], $message['return_msg']??'');

                return $fail('notify_fail');
            }
        });
        //$response = $app->server->serve();
        return $response->getContent();
    }


}
